package com.cqw.controller;

import com.cqw.service.ThreadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-06-08 14:45
 * @Description: 线程测试api
 */
@RestController
public class ThreadController {

    @Autowired
    private ThreadService threadService;


    @Autowired
    private ExecutorService executorService;


    @GetMapping("/test1")
    public String test1() {
        threadService.test1();
        return "OK";
    }


    @GetMapping("/test2")
    public String test2() {
        CompletableFuture<String> future = threadService.test2();
        System.out.println("拿到了返回值，此时线程没有结束");
        try {
            String s = future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return "OK";
    }


    @GetMapping("/test3")
    public String test3() {
        executorService.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("我是线程中的内容");
        });
        return "OK";
    }


    @GetMapping("/test4")
    public String test4() {
        Future<String> submit = executorService.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("我是线程中的内容");
            return "我是线程返回值";
        });
        String s = null;
        try {
            s = submit.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(s);
        return "OK";
    }


}
